<template>
  <div style="margin-bottom: 15px">
    <el-table :data="fileResult" stripe border  :header-cell-style="{background:'#eee',color:'#606266',fontSize: '12px'}">
      <!-- 索引列 -->
      <el-table-column label="序号" type="index"></el-table-column>
      <el-table-column label="文件名称" prop="ImportName" width="250px"></el-table-column>
      <el-table-column label="文件类型" prop="ImportType" width="250px"></el-table-column>
      <el-table-column label="上传要求" prop="ImportName" width="250px">
        <template slot-scope='scope'>
          {{scope.row.IsReq ? '必须上传' : '非必须上传'}}
        </template>
      </el-table-column>
      <el-table-column label="上传描述">
        <template slot-scope='scope'>
          只能上传所需材料的{{scope.row.ImportType}}文件
        </template>
      </el-table-column>
      <el-table-column label="文件示例" width="80px">
        <template v-slot="{ row }">
          <span v-if="!row.ImportPicBase64 || !row.examplePicType">暂无示例</span>
         <el-button v-else type="text" @click="showPrePic(row)" size="small">查看示例</el-button>
        </template>
      </el-table-column>
      <el-table-column label="文件状态" prop='ImportType' width="150px">
        <template slot-scope="scope">
          <el-tag type="success" v-if="scope.row.IsUpload">上传成功</el-tag>
          <el-tag type="info" v-else>尚未上传</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="文件操作">
        <template slot-scope="scope">
          <el-upload
            class="upload-demo"
            :ref="'uploadRef' + scope.$index"
            action=""
            :limit="1"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :on-exceed="handleExceed"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="text">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="text" @click="submitUpload(scope.row.ImportType, scope.$index)">上传</el-button>
            <el-button size="small" type="text" @click="handleRemove(scope.$index)">删除文件</el-button>
          </el-upload>
        </template>
      </el-table-column>
    </el-table>
    <!-- 显示预览图片 -->
    <div class='prePic' v-show="isShowPrePic" >
      <i class="el-icon-close" @click="isShowPrePic = false"></i>
      <el-image
        fit='cover'
        :z-index="9999"
        style="width: 450px; height: 450px"
        :src="this.prePicUrl"
        :preview-src-list="previewList"
      >
      </el-image>
    </div>
  </div>
</template>

<script>
import toBlob from '@/utils/toblob'
export default {
  props: ['allowanceId', 'showAllFiles'],
  data() {
    return {
      // 本次补贴信息
      businessInfo: {},
      prePicUrl: '', // 示例图片前端生成的地址
      defaultPrePic: require('@/assets/images/noPrePic.png'),
      isShowPrePic: false, // 控制图片显示隐藏
      previewList: []
    }
  },
  watch: {
    allowanceId(newVal) {
     // 拿到父传子的补贴id新值之后再去获取补贴文件信息
     this.getBusinessInfo()
    }
  },
  computed: {
    fileResult() {
     // false显示全部，true显示必传
      if (this.businessInfo && this.businessInfo.Imports) {
        if (this.showAllFiles) {
          const reqFilesList = this.businessInfo.Imports.filter(item => item.IsReq === 1)
          return reqFilesList
        } else {
          return this.businessInfo.Imports
        }
      }
    }
  },
  methods: {
    // 获取需要上传的补贴文件信息
    async getBusinessInfo () {
     const { data: { data: res } } = await this.$http.get('/allowance/fetchImportList', { params: {
        allowanceId: this.allowanceId
      }})
      this.businessInfo = res
    },
    // 上传文件
    async submitUpload(fileType,index) {
      fileType = fileType.split(',')
      console.log(index)
      // 确定要上传的是哪个文件选择器
      const ref = 'uploadRef' + index
      if (this.$refs[ref].uploadFiles.length === 0) {
        // 文件为空时
        return this.$message.warning('尚未选择文件')
      }
      // 1. 获取要上传的文件,raw是一个File对象
      const file = this.$refs[ref].uploadFiles[0].raw
      console.log(file)
      // 判断文件类型
      const symbolIndex = file.name.lastIndexOf('.') // .的下标
      const realType = file.name.substr(symbolIndex + 1) // 文件类型后缀
      if (fileType.indexOf(realType) === -1) {
        this.$refs[ref].uploadFiles = []
        return this.$alert('您选择的文件类型不符合上传要求，请重新选择！', '错误提示', {
          confirmButtonText: '好的，我知道了'
        })
      }
      let fd = new FormData()
      fd.append('file', file)
      // 2. 上传的必备信息
      const tempUploadfileInfo =  JSON.stringify({
        allowanceId: this.allowanceId,
        busiIds: this.businessInfo.Busiid,
        channelCode: this.businessInfo.ChannelCode,
        gjjzh: sessionStorage.getItem('gjjzh'),
        imUuid: this.businessInfo.Imports[index].ImUUid,
        seviceCode: this.businessInfo.SeviceCode
      })
      fd.append('tempUploadfileInfo', new Blob([tempUploadfileInfo], {type: "application/json"}))
      // 3. 调用上传接口
      const { data: res }  = await this.$http.post('/allowance/uploadAllowanceFile', fd)
      if (res.code !== 200) {
        this.$message.error(res.msg)
      } else {
        // 更新文件状态
        this.businessInfo.Imports[index].IsUpload = true
      }
    },
    handleExceed() {
      this.$message.warning('只允许上传单个文件！如有调整，请移除文件后重新上传！')
    },
    // 删除文件
    async handleRemove(index) {
      const { data: res } = await this.$http.delete('/allowance/deleteAllowanceFile', { params: {
          allowanceId: this.allowanceId,
          busiid: this.businessInfo.Busiid,
          imuuid: this.businessInfo.Imports[index].ImUUid
        }})
      if (res.code !== 200) {
        this.$message.error(res.msg)
      } else {
        // 更新文件状态
        this.businessInfo.Imports[index].IsUpload = false
      }
    },
    // 删除前钩子
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    // 预览示例图片
    showPrePic(ImageInfo) {
      this.previewList = []
      // 图片前端地址
      let fileURL = window.URL.createObjectURL(toBlob(ImageInfo.ImportPicBase64, ImageInfo.examplePicType.substr(1), true))
      console.log(fileURL)
      this.previewList.push(fileURL)
      this.prePicUrl = fileURL
      // 显示预览图片的盒子
      this.isShowPrePic = true
    }
  }
}
</script>

<style lang="less" scoped>
//.prePic {
//  position: fixed;
//  top: 50%;
//  left: 60%;
//  transform: translate(-50%, -50%);
//  z-index: 666;
//
//  //img {
//  //  width: 300px;
//  //  height: 300px;
//  //  object-fit: contain;
//  //}
//
//  &::before {
//    content: "单击放大";
//    display: block;
//    text-align: center;
//    font-weight: bold;
//    color: red;
//  }
//
//  .el-icon-close {
//    border: 1px solid #373d41;
//    border-radius: 6px;
//    position: absolute;
//    font-size: 12px;
//    top: 5px;
//    right: 0;
//    cursor: pointer;
//  }
//}
.prePic {
  position: fixed;
  top: 40%;
  left: 60%;
  transform: translate(-50%, -50%);
  z-index: 9998;

  &::before {
    content: "提示：单击图片放大";
    display: block;
    text-align: center;
    font-weight: bold;
    color: red;
    background-color: #cfe8fc;
  }

  .el-icon-close {
    border: 2px solid #1e2225;
    font-weight: 700;
    border-radius: 7px;
    position: absolute;
    font-size: 14px;
    top: 1px;
    right: 0;
    cursor: pointer;
  }
  .el-icon-close:hover {
    color: red;
    border: 2px solid red;
  }
}
</style>
